package com.situ.day8.exception;

import org.junit.Test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ExceptionDemo {
    @Test
    public void test1() {
        //java.lang.ArithmeticException: / by zero
        int num = 3 / 0;
    }

    @Test
    public void test2() {
        String str = "hello";
        char ch1 = str.charAt(4);
        System.out.println(ch1);
        //java.lang.StringIndexOutOfBoundsException: String index out of range: 5
        char ch2 = str.charAt(5);
        System.out.println(ch2);
    }

    @Test
    public void test31() {
        //Unhandled exception: java.lang.ClassNotFoundException
        // try-catch自己处理这个异常
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void test3() throws ClassNotFoundException {
        //Unhandled exception: java.lang.ClassNotFoundException
        //throws：我自己不处理，把这个异常抛出，谁调用这个方法谁去处理
        Class.forName("com.mysql.jdbc.Driver");
    }

    @Test
    public void test4() {
        try {
            //需要检查的代码（可能会抛出异常，也可能不会抛出异常）
            FileInputStream fileInputStream = new FileInputStream("a.txt");
            System.out.println("try....");
        } catch (FileNotFoundException e) {
            //捕获异常后要处理异常
            e.printStackTrace();
        } finally {
            //一定会被执行的代码（不管异常抛不抛出都会执行）
            System.out.println("finally...");
        }
    }

    @Test
    public void test5() {
        fun();
        System.out.println("ExceptionDemo.test5");
    }

    public void fun() {
        try {
            FileInputStream fileInputStream = new FileInputStream("a.txt");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void test6() {
        //fun1();

        try {
            System.out.println("ExceptionDemo.test6");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void fun1() throws FileNotFoundException {
        FileInputStream fileInputStream = new FileInputStream("a.txt");
    }

    @Test
    public void test7() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/java2303?useUnicode=true&characterEncoding=UTF-8", "root", "1234");
        } /*catch (Exception e) {
            e.printStackTrace();
        }*/ catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }
    }
}
